// index.js
const app = getApp();

Page({
  data: {
    temperature: 25,
    humidity: 50,
    heaterStatus: false,
    password: ['', '', '', ''],
    focus0: false,
    focus1: false,
    focus2: false,
    focus3: false,
    currentFocus: 0,
    showPasswordInput: false,
    isProcessing: false,
    connectButtonText: '连接服务器',
  },

  onLoad() {
    // 注册页面到app.js
    app.registerPage(this);
    
    // 初始化数据
    this.setData({
      temperature: app.globalData.temperature,
      humidity: app.globalData.humidity,
      heaterStatus: app.globalData.heaterStatus,
      status:app.globalData.status,
      password:app.globalData.password || ['', '', '', ''] ,
      id:app.globalData.id,
      connectButtonText: this.getConnectButtonText(app.globalData.mqttStatus)
    });
  },

  onUnload() {
    // 注销页面
    app.unregisterPage(this);
  },

  onShow() {
    // 从后台唤醒时检查连接
    if (app.globalData.mqttStatus === 'disconnected') {
      this.connectToMqtt(this.globalData.mqttHost);
    };
    app.initUserRole(app.globalData.userRoles.admin)

  },

  onHide() {
    // 进入后台时清理心跳
    if (this._heartbeatTimer) clearInterval(this._heartbeatTimer);
  },
  
  // 更新数据的方法，由app.js调用
  updateData(data) {
    this.setData(data);
  },

  getConnectButtonText(status) {
    switch(status) {
      case 'connected': return '已连接';
      case 'connecting': return '连接中...';
      case 'disconnected': return '连接服务器';
      default: return '连接服务器';
    }
  },
    // 保存状态到本地存储
    saveCurrentState() {
      wx.setStorageSync('indexState', {
        password: this.data.password,
        doorStatus: this.data.doorStatus,
        heaterStatus: this.data.heaterStatus,
        currentPassword: this.data.currentPassword
      });
    },
    //
    loadCurrentState() {
      const state = app.getCurrentState();
      this.setData({
        heaterStatus: state.isHeated,
        doorStatus: state.isDoorOpened,
        currentPassword: state.newPassword
      });
    },

  checkProcessing() {
    if (this.data.isProcessing) {
      wx.showToast({ title: '请等待当前操作完成', icon: 'none' });
      return true;
    }
    this.setData({ isProcessing: true });
    return false;
  },

  toggleDoor() {
    if (this.checkProcessing()) return;
    const success = app.sendCommand({ door: "33" });
    if (success) {
      wx.showToast({ title: '正在开门...', icon: 'loading' });
      app.updateDeviceState({ isDoorOpened: true });
    }
    setTimeout(() => this.setData({ isProcessing: false }), 5000);
  },

  toggleHeater() {
    if (this.checkProcessing()) return;
    const newStatus = !this.data.heaterStatus;
    app.updateDeviceState({ isHeated: newStatus });
    this.setData({ heaterStatus: newStatus });
    const success = app.sendCommand({ heater: newStatus ? 123 : 234 });
    if (!success) {
      this.setData({ heaterStatus: !newStatus });
    }
    setTimeout(() => this.setData({ isProcessing: false }), 5000);
  },

  // 处理密码输入
  handlePasswordInput(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const value = e.detail.value;
    
    // 安全处理：确保始终使用数组
    const currentPassword = this.data.password || ['', '', '', '']; // 防御undefined
    const newPassword = [...currentPassword]; 
    
    newPassword[index] = value.replace(/\D/g, '');
    this.setData({ password: newPassword });

    // 自动切换焦点
    if (value && index < 3) {
      this.setData({
        [`focus${index}`]: false,
        [`focus${index + 1}`]: true
      });
    }
  },

  // 确认密码
  confirmPassword() {
    const app = getApp();
    const passwordArray = this.data.password;
    // 双重类型校验
    if (!Array.isArray(passwordArray)) {
      wx.showToast({ title: '密码数据异常', icon: 'error' });
      return;
    }
    if (passwordArray.some(c => c === undefined || c === null)) {
      wx.showToast({ title: '存在未输入的密码位', icon: 'none' });
      return;
    }
    const password = passwordArray.join('');
    // 发送MQTT指令
    const success = app.sendCommand({
      password: password
    });
    if (success) {
      // 存入历史记录
      app.updateDeviceState({
        newPassword: this.data.password
      });
      
      // 清空输入
      this.setData({
        password: ['', '', '', ''],
        focus0: true,
        focus1: false,
        focus2: false,
        focus3: false
      });
      
      wx.showToast({ title: '密码已更新', icon: 'success' });
    }
  },


gotonext()
{
  wx.navigateTo({
    url: '/pages/index/index'
  }) 
}



});